package com.sunjie.core;

import java.io.Serializable;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sunjie.bean.TableBean;
import com.sunjie.bean.TableCellBean;
import com.sunjie.utils.CovertUtils;

/**
 * @author sj
 * @date 2018/1/25
 */
@Component
public class DataMessageImpl implements DataMessage {

    private static final Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);

    @Autowired
    private DataSource          dataSource;

    @Override
    public List<TableBean> loadDataMeta() {
        List<TableBean> tableBeans = new ArrayList<>();
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        List<String> tables = getTable(connection);
        TableBean tableBean;
        for (String table : tables) {
            tableBean = new TableBean();
            if (table.charAt(1) == '_') {
                //如果表名称第二个为_ 去掉
                tableBean.setTableName(CovertUtils.replaceUnderLineAndUpperCase(table.substring(2)));
            } else {
                tableBean.setTableName(CovertUtils.replaceUnderLineAndUpperCase(table));
            }
            tableBean.setTableCellBeans(getCell(connection, table));
            tableBeans.add(tableBean);
        }
        return tableBeans;

    }

    /**
     * 获取表中所有字段名称
     * 
     * @param connection
     * @return
     */
    private List<String> getTable(Connection connection) {
        List<String> tableNames = new ArrayList<>();
        DatabaseMetaData metaData = null;
        ResultSet rs = null;
        try {
            metaData = connection.getMetaData();
            rs = metaData.getTables(null, null, null, new String[] { "TABLE" });
            while (rs.next()) {
                tableNames.add(rs.getString("TABLE_NAME"));
                logger.info("加载表名称:" + rs.getString("TABLE_NAME"));
            }
        } catch (SQLException e) {
            logger.error("加载表数据失败");
        }
        logger.info("-----------加载表名称完成------------");
        return tableNames;
    }

    /**
     * 获取表中所有字段类型
     * 
     * @param connection
     * @return
     */
    private List<TableCellBean> getCell(Connection connection, String table) {
        List<TableCellBean> tableCellBeans = new ArrayList<>();
        ResultSetMetaData meta = null;
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            String sql = "select * from " + table;
            ps = connection.prepareStatement(sql);
            rs = ps.executeQuery();
            meta = rs.getMetaData();
            int columeCount = meta.getColumnCount();
            TableCellBean tableCellBean = null;
            for (int i = 1; i < columeCount + 1; i++) {
                tableCellBean = new TableCellBean();
                tableCellBean
                        .setName(CovertUtils.replaceUnderLineAndUpperCase(meta.getColumnName(i)));
                tableCellBean.setSqlTypeName(meta.getColumnTypeName(i));
                tableCellBean
                        .setJavaTypeName(CovertUtils.sqlType2JavaType(meta.getColumnTypeName(i)));
                tableCellBeans.add(tableCellBean);
            }

        } catch (SQLException e) {
            logger.error("加载表内数据失败");
        }
        return tableCellBeans;
    }

}
